var myApp = sy.getModule('myApp',[]);
myApp.directive('onFinishRenderFilters', function ($timeout) {
    return {
        restrict: 'A',
        link: function(scope, element, attr) {
            if (scope.$last === true) {
                $timeout(function() {
                    scope.$emit('ngRepeatFinished',attr.onFinishRenderFilters);
                });
            }
        }
    };
});
myApp.controller('myController', function($scope,$http,$location, $anchorScroll) {
  $scope.cateId = '';
  $scope.storeId = _id;
  $scope.store= {};
  $scope.list = [];
  $scope.active = {};
  $scope.cart = {storeId:'',storeName:'',num:0,price:0,packPrice:0,remain:0};
  $scope.cartList = {};
  $scope.isThisStore = false;
  $scope.cate = function(cateId){
	  $scope.cateId = cateId;
	  $location.hash(cateId);
	  $anchorScroll();
  };
  
//加载购物车本地数据
	$scope.initHistory = function(){
		var str = sessionStorage.cartRestaurant;
		var cart = {};
		var flag = true;
		if (str != undefined && str != '') {
			cart = sy.stringToJSON(str);
			if(cart.num > 0){
				//菜单
				str = sessionStorage.cartList;
				var cartList = {};
				if (str != undefined && str != '{}') {
					cartList = sy.stringToJSON(str);
					$scope.cartList = cartList;
					$scope.cart = cart;
					if($scope.cart.storeId == $scope.store.id){
						//初始化菜单
						$.each($scope.list,function(i,o){
							$.each(o.goods.goodsList,function(j,q){
								if($scope.cartList[q.id]){
									q.num = $scope.cartList[q.id].num;
								}
							});
						});
						flag = false;
						$scope.isThisStore = true;
						isThisStore = $scope.isThisStore;
					}
				}
			}
		}
		
		if(flag){
			$scope.isThisStore = true;
			isThisStore = $scope.isThisStore;
			$scope.cart.remain = 0;
			$scope.cart.storeId = $scope.store.id;
			$scope.cart.storeName = $scope.store.name;
			
			sessionStorage.cartRestaurant = sy.jsonToString($scope.cart);
			
			sessionStorage.cartList = sy.jsonToString($scope.cartList);
		}
	}
	
  
  $scope.nextPage = function() {
      sy.openLoad();
      $http.post(sy.path + "/m/store/goodsList",{
    	  		id:_id
      		})
			.success(function (data) {
				$scope.list = data.data.data;
				$scope.store = data.data.store;
				$scope.cateId = $scope.list[0].cate.id;
				$.each($scope.list,function(i,o){
					$.each(o.goods.goodsList,function(j,q){
						if (!q.num)
							q.num=0;
					});
				});
				$scope.initHistory();
	            sy.closeLoad();
	        }).error(function(data, status) {
	        	sy.closeLoad();
			});
  };
  $scope.nextPage();
  $scope.$on('ngRepeatFinished', function (event,data) {
		if(data == 'goods'){
			/*$(".Spinner").each(function() {
		        $(this).Spinner();
		    });*/
		}
		loaded();
		$(document).ready(function() {	//tbl切换
	        $(".ot-menu  li").click(function(){
	            tabIndex = $(this).index();
	            $(this).siblings("li").removeClass("active");
	            $(this).addClass("active");
	            $(".ot-maininfo").children(".menutype").hide();
	            $(".ot-maininfo").children(".menutype").eq(tabIndex).show();
	            var cId = $(this).attr('cid');
	            var top = $('#right_Menu').find('div[cid='+cId+']').offset().top;
	            var now = $('#scroller2').offset().top;
	            myScroll_right.scrollTo(0,now-top,1000);
	        });
	    });
	});
  
  $scope.add = function(g,flag){
			//if(g.total > g.num){
				var add = true;
				if(!$scope.isThisStore){
					if(confirm("您的美食篮子里有其它餐厅的美食，清空美食篮子吗？")){
						$scope.cart = {storeId:$scope.store.id,storeName:$scope.store.name,num:0,price:0,packPrice:0,remain:0};
						sessionStorage.cartRestaurant = sy.jsonToString($scope.cart);
						$scope.isThisStore = true;
						
						$scope.cartList = {};
						sessionStorage.cartList = sy.jsonToString($scope.cartList);
					}else{
						add = false;
					}
				}
				
				if(add){
					g.num++;
					$scope.cart.num++;
					$scope.cart.price = Math.formatFloat($scope.cart.price+parseFloat(g.price),2);
					$scope.cart.packPrice = 0;
					
					$scope.cart.remain = 0;
					sessionStorage.cartRestaurant = sy.jsonToString($scope.cart);
					
					$scope.cartList[g.id] = {id:g.id,name:g.name,num:g.num,max:0,total:0,price:g.price};
					sessionStorage.cartList = sy.jsonToString($scope.cartList);
				}
				if(flag){
					$.each($scope.list,function(i,o){
						$.each(o.goods.goodsList,function(j,q){
							console.log(q);
							if(q.id==g.id){
								q.num = g.num;
							}
						});
					});
					$.each($scope.store.cate,function(i,o){
						 $.each(o.goods,function(j,obj){
							 if(obj.id==g.id){
									$scope.store.cate[i].goods[j].num = g.num;
								}
						 });
					});
				}
			//}else{
			//	sy.alert("库存不足");
			//}
		};
  
//减
	$scope.minus = function(g,flag){
		if(g.num > 0){
			var del = true;
			if(!$scope.isThisStore){
				if(confirm("您的美食篮子里有其它餐厅的美食，清空美食篮子吗？")){
					$scope.cart = {storeId:$scope.store.id,storeName:$scope.store.name,num:0,price:0,packPrice:0,remain:0};
					sessionStorage.cartRestaurant = sy.jsonToString($scope.cart);
					$scope.isThisStore = true;
					
					$scope.cartList = {};
					sessionStorage.cartList = sy.jsonToString($scope.cartList);
					
					del = false;
				}
			}
			
			if(del){
				g.num--;
				$scope.cart.num--;
				$scope.cart.price=Math.formatFloat($scope.cart.price - parseFloat(g.price),2);
				$scope.cart.packPrice=0;

				$scope.cart.remain = 0;
				
				sessionStorage.cartRestaurant = sy.jsonToString($scope.cart);
				
				if(g.num > 0){
					$scope.cartList[g.id] = {id:g.id,name:g.name,num:g.num,max:g.max,total:g.total,price:g.price};
				}else{
					delete $scope.cartList[g.id];
				}
				sessionStorage.cartList = sy.jsonToString($scope.cartList);
			}
			if(flag){
				$.each($scope.list,function(i,o){
					$.each(o.goods.goodsList,function(j,q){
						console.log(q);
						if(q.id==g.id){
							q.num = g.num;
						}
					});
				});
				$.each($scope.store.cate,function(i,o){
					 $.each(o.goods,function(j,obj){
						 if(obj.id==g.id){
								$scope.store.cate[i].goods[j].num = g.num;
							}
					 });
				});
				if(!$scope.cartList||count($scope.cartList)==0){
					$(".bg_cart").toggleClass("hide");
				}
			}
		}
	}

  Math.formatFloat = function(f, digit) { 
	    var m = Math.pow(10, digit); 
	    return parseInt(f * m, 10) / m; 
	} 
  
  $scope.goDetail = function(id){
	  location.href = sy.path + "/m/goods/"+id;
  }
  
//提交订单
	$scope.goSubmit = function(){
		var cart = sy.stringToJSON(sessionStorage.cartRestaurant);
		if(cart.num > 0){
			location.href = sy.path + "/m/store/addDiacan/"+_id;
		}
	};
});

function count(o){
    var t = typeof o;
    if(t == 'string'){
            return o.length;
    }else if(t == 'object'){
            var n = 0;
            for(var i in o){
                    n++;
            }
            return n;
    }
    return false;
}; 
